package com.meizu.asum.richtextsdk.span;

import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.text.style.ImageSpan;

import com.meizu.asum.richtextsdk.config.RichTextAlignment;

public class EmoticonSpan extends ImageSpan {
    private RichTextAlignment textAlignment;

    public EmoticonSpan(Drawable drawable, RichTextAlignment textAlignment) {
        super(drawable);
        this.textAlignment = textAlignment;
    }

    public int getSize(Paint paint, CharSequence text, int start, int end, Paint.FontMetricsInt fontMetricsInt) {
        Drawable drawable = getDrawable();
        Rect rect = drawable.getBounds();
        if (fontMetricsInt != null) {
            Paint.FontMetricsInt fmPaint = paint.getFontMetricsInt();
            //文本高度
            int fontHeight = fmPaint.bottom - fmPaint.top;
            //图片高度
            int picHeight = rect.bottom - rect.top;

            if (textAlignment == RichTextAlignment.VERTICAL_CENTER) {
                int top = picHeight / 2 - fmPaint.descent;
                int bottom = picHeight / 2 + fmPaint.descent;

                fontMetricsInt.ascent = -bottom;
                fontMetricsInt.top = -bottom;
                fontMetricsInt.bottom = top;
                fontMetricsInt.descent = top;
            } else if (textAlignment == RichTextAlignment.BOTTOM) {
                fontMetricsInt.ascent = -picHeight;
                fontMetricsInt.top = -picHeight;
                fontMetricsInt.bottom = fmPaint.bottom;
                fontMetricsInt.descent = fmPaint.bottom;
            }
        }
        return rect.right;
    }

    public void draw(Canvas canvas, CharSequence text, int start, int end, float x, int top, int y, int bottom, Paint paint) {
        Drawable drawable = getDrawable();
        canvas.save();

        int transY = 0;
        if (textAlignment == RichTextAlignment.VERTICAL_CENTER) {
            transY = ((bottom - top) - drawable.getBounds().bottom) / 2 + top;
        } else if (textAlignment == RichTextAlignment.BOTTOM) {
            transY = bottom - drawable.getBounds().bottom;
        }

        canvas.translate(x, transY);
        drawable.draw(canvas);
        canvas.restore();
    }
}